﻿using Bigway.Common.Interfaces;
using Bigway.Common.Services;
using Bigway.Common.Services.Repositories;
using Extensions.Hosting.AsyncInitialization;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;

namespace Bigway.Common;

public class CommonInitializer(ISoftwareSystemRepository softwareSystemRepository, 
    IServiceProvider sp, 
    SqliteConnectionConfig sqliteConnectionConfig,
    CrmebConnectionConfig crmebConnectionConfig,
    SqlLogger sqlLogger,
    SqliteDbInfo dbInfo) : IAsyncInitializer
{
    public async Task InitializeAsync(CancellationToken cancellationToken)
    {
        sqliteConnectionConfig.AopEvents.OnLogExecuting = sqlLogger.Log;
        crmebConnectionConfig.AopEvents.OnLogExecuting = sqlLogger.Log;
        var sqliteClient = sp.GetRequiredKeyedService<ISqlSugarClient>(IocKeys.SqliteDbKey);
        if (!File.Exists(dbInfo.FilePath))
        {
            sqliteClient.DbMaintenance.CreateDatabase(dbInfo.Name, null);
        }
        sqliteClient.CodeFirst.InitTables(dbInfo.EntityTypes);
        await softwareSystemRepository.InitializeAllAsync(cancellationToken);
    }
}